package com.mingweicai.intergration.thread.pcM;

import java.util.ArrayList;
import java.util.List;

class Box {

  List<Object> apples = new ArrayList<>();

  public synchronized void putApple() {
    if(apples.size()>=5){
      try {
        wait();
      } catch (InterruptedException e) {
        e.printStackTrace();
      }
    }
    apples.add("apple");
    System.out.println("放苹果，个数" + apples.size());
    notifyAll();
  }

  public synchronized void getApple(){
    if(apples.size() == 0){
      try {
        wait();
      } catch (InterruptedException e) {
        e.printStackTrace();
      }
    }
    Object apple = apples.remove(apples.size() -1);
    System.out.println("-----取苹果，个数" + apples.size());
    notifyAll();
  }

}

class Producer implements Runnable{

  Box box;

  public Producer(Box box) {
    this.box = box;
  }

  @Override
  public void run() {
    while(true){
      box.putApple();
    }
  }
}

class Consumer implements Runnable{
  Box box;

  public Consumer(Box box) {
    this.box = box;
  }

  @Override
  public void run() {
    while(true){
      box.getApple();
    }
  }
}

public class Main {

  public static void main(String args[]){
    Box box = new Box();
    Producer producer = new Producer(box);
    Consumer consumer = new Consumer(box);

    new Thread(producer).start();
    new Thread(consumer).start();
  }
}
